package leetcode;

import java.util.*;

public class LC3 {
    public static void main(String[] args) {
        LC3 lc3 = new LC3();
        System.out.println(lc3.longestConsecutive2(new int[]{100,4,200,1,3,2}));
        System.out.println(lc3.longestConsecutive2(new int[]{0,0,-1}));
        System.out.println(lc3.longestConsecutive(new int[]{4,0,-4,-2,2,5,2,0,-8,-8,-8,-8,-1,7,4,5,5,-4,6,6,-3}));
        System.out.println(lc3.longestConsecutive(new int[]{100,4,200,1,3,2}));
        System.out.println(lc3.longestConsecutive(new int[]{1,2,0,1}));
        System.out.println(lc3.longestConsecutive(new int[]{0,3,7,2,5,8,4,6,0,1}));
    }
    //2021-11-20 回顾
    public int longestConsecutive3(int[] nums) {
        Arrays.sort(nums);
        int left = 0, right = 1;
        int ans = 0;
        int c = 0;
        while(left < nums.length && right < nums.length){
            if (nums[right] == nums[right - 1]){
                c++;
            }
            else if(nums[right] != nums[right - 1] + 1) {
                ans = Math.max(ans,right-left- c);
                c = 0;
                left = right;
            }
            right++;
        }
        ans = Math.max(ans,right-left- c) ;
        return ans;
    }

    public int longestConsecutive2(int[] nums){
        if(nums.length == 0) return 0;
        Arrays.sort(nums);
        int max = 1;
        int m = 1;
        for (int i = 1; i < nums.length; i++) {
            if(nums[i] == nums[i-1] + 1){
                max = Math.max(++m,max);
            } else if (nums[i] == nums[i - 1]) {
            }else {
                m = 1;
            }
        }
        return max;
    }
    public int longestConsecutive(int[] nums) {
        Arrays.sort(nums);
        Map<Integer, List<Integer>> map = new HashMap<>();
        ArrayList<Integer> list = new ArrayList<>();
        list.add(nums[0]);
        map.put(nums[0],list);
        for (int i = 1; i < nums.length; i++) {
            if (!map.containsKey(nums[i])) {
                if (map.containsKey(nums[i]-1)){
                    List<Integer> integers = map.get(nums[i]-1);
                    integers.add(nums[i]);
                    map.put(nums[i],integers);
                    map.put(nums[i]-1,integers);
                }else if (map.containsKey(nums[i]+1)){
                    List<Integer> integers = map.get(nums[i]+1);
                    integers.add(nums[i]);
                    map.put(nums[i],integers);
                    map.put(nums[i]+1,integers);
                }else{
                    ArrayList<Integer> integers = new ArrayList<>();
                    integers.add(nums[i]);
                    map.put(nums[i],integers);
                }
            }
        }
        int max = 0;
        for (List<Integer> value : map.values()) {
            max = Math.max(max,value.size());
        }
        return max;
    }
}
